package com.minelx.datamicroscope.querylanguage.data.sql;

import com.alibaba.druid.sql.ast.statement.*;
import com.minelx.datamicroscope.querylanguage.data.CollectingField;
import com.minelx.datamicroscope.querylanguage.data.CollectingKey;

import java.util.Collections;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class SelectItemsFactory {

	public static List<SelectItem> single(SQLSelectQueryBlock firstQueryBlock) {
		CollectingKey collectingKey = new CollectingKey(
				tableLocateAsText0((SQLExprTableSource) firstQueryBlock.getFrom()),
				Collections.emptyMap(),
				Collections.emptyList());

		// fulfill selected items
		return firstQueryBlock.getSelectList().stream()
				.map(CollectingField::of)
				.map(collectingField -> new SelectItem(collectingKey, collectingField))
				.collect(toList());
	}

	public static List<SelectItem> joined(SQLSelectQueryBlock firstQueryBlock, AliasedTables build) {
		return build.createSelectItems(firstQueryBlock.getSelectList()).stream()
				.map(TableAliasedSelectItem::getSelectItem)
				.collect(toList());
	}

	public static String tableLocateAsText0(SQLExprTableSource fromTableSource) {
		String content = fromTableSource.toString();
		return content.substring(1, content.length() - 1);
	}
}
